// 拆分计算阶段和格式化阶段
function createStatement(invoice, plays) {

  let result = {};
  result.customer = invoice.customer;
  result.performances = invoice.performances.map(enrichPerformance);
  result.totalAmount = totalAmount(result);
  result.totalVolumeCredits = totalVolumeCredits(result);
  return result;

  // 内联变量
  function playFor(performance) {
    return plays[performance.playID]
  }

  // 提炼函数，计算戏剧对应金额
  function amountFor(performance) {
    let result = 0;
    switch (performance.play.type) {
      case "tragedy":
        result = 40000;
        if (performance.audience > 30) {
          result += 1000 * (performance.audience - 30);
        }
        break;
      case "comedy":
        result = 30000;
        if (performance.audience > 20) {
          result += 10000 + 500 * (performance.audience - 20);
        }
        break;
      default:
        throw new Error(`unknown type: ${performance.play.type}`);
    }
    return result;
  }

  // 提炼函数，计算戏剧对应积分
  function volumeCreditsFor(performance) {
    let result = 0;
    // 增加积分
    // add volume credits
    result += Math.max(performance.audience - 30, 0);
    // 为什么是除以5呢？ 如果是除以10的话，大于5小于10的结果就是0
    // 如果是喜剧类型的戏剧，每多10个听众就增加1积分
    // add extra credit for every ten comedy attendees
    if ("comedy" === performance.play.type) {
      result += Math.floor(performance.audience / 5);
    }

    return result;

  }

  // 填充performance对象
  function enrichPerformance(performance) {
    const result =  Object.assign({}, performance);
    result.play = playFor(performance);
    result.amount = amountFor(result);
    result.volumeCredits = volumeCreditsFor(result);
    return result;
  }

  // 代码搬移，计算总金额
  function totalAmount(statementData) {
    return statementData.performances.reduce((prev, curr) => prev + curr.amount, 0);
  }

  // 代码搬移，计算总积分
  function totalVolumeCredits(statementData) {
    return statementData.performances.reduce((prev, curr) => prev + curr.volumeCredits, 0);
  }

}

export { createStatement };